/* $Id: misc.cc jjs $ */
/*
   Copyright (C) 2007 by Jurjen Stellingwerff <jurjen@stwerff.xs4all.nl>
   Part of the Moros Project http://moros.sourceforge.net/

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License version 2 or any
   later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY.

   See the COPYING file for more details.
*/

#define DEBUG_ROUTINE "misc"

#include "misc.h"
#include "gcrypt.h"
#include <sstream>
#include "log.h"

using namespace std;

const char hex_tbl[] = "0123456789abcdef";

std::string hash(std::string str) {
	gcry_md_handle *hashv;
	string res="";
	gcry_md_open(&hashv, GCRY_MD_SHA1, 0);
	gcry_md_write( hashv, str.c_str(), str.length() );
	gcry_md_final( hashv );
	unsigned char *code=gcry_md_read(hashv,GCRY_MD_SHA1);
    int i;
    for (i = 0; i < 20; i++) {
        res += hex_tbl[code[i] >> 4];
        res += hex_tbl[code[i] & 0xf];
    }
	gcry_md_close(hashv);
	return res;
}

std::string subs(std::string s, size_t from, size_t len) {
    if (from>=s.length()) return "";
    return s.substr(from, len);
}

std::string derived(std::string session, int sessnr) {
    ostringstream streamOut;
    streamOut << subs(session, sessnr % 20, string::npos) << subs(session, 0, sessnr % 20) << sessnr;
    string res=hash(streamOut.str()).substr(0,10);
    dbg_calls("derived `%s`,`%d` = `%s`", session.c_str(), sessnr, res.c_str());
    return res;
}
